package com.eystar.pdc.model;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.eystar.ext.kit.ContainerKit;
import com.eystar.ext.kit.page.PageOrder;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

/**
 * 字典项 Model
 * 
 * @author Your_Name
 * 
 */
@TableBind(tableName = "t_pdc_dic_item")
public class DicItem extends ModelExt<DicItem> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static DicItem dao = new DicItem();

	/**
	 * 分页查找对象
	 *
	 * @param order
	 * @param user
	 * @return
	 */
	public Page<DicItem> paginate(PageOrder order, DicItem dicItem) {
		SqlPara sqlPara = getSqlPara("pdc.dic_item.paginate",dicItem);
		return paginate(order.getPageNum(), order.getPageSize(), sqlPara);
	}

	/**
	 * 根据字典ID的值查找字典项
	 * @param dicId
	 * @return
	 */
	public Map<String, String> findDicItemByDicId(String dicId) {
		Map<String, String> ret = new HashMap<String, String>();
		List<DicItem> dicItems = DicItem.dao.findByColumnSecurity("dic_id", dicId);
		for (DicItem dicItem : dicItems) {
			ret.put(dicItem.getStr("item_code"), dicItem.getStr("item_value"));
		}
		return ret;
	}
	/**
	 * 根据字典ID的值查找字典项
	 * @param dicId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> findDicItems(String dicCode) {
		if (!ContainerKit.contains("dic")) {
			ContainerKit.put("dic",DicItem.dao.findDicItems());
		}
		LinkedHashMap<String, LinkedHashMap<String, String>> map = (LinkedHashMap<String, LinkedHashMap<String, String>>) ContainerKit.get("dic");
		return map.get(dicCode);
	}
	/**
	 * 根据字典编码和字典项编码查找某个字典项的值
	 * @param dicCode
	 * @param itemCode
	 * @return
	 */
	public String findDicItemValue(String dicCode,String itemCode) {
		Map<String, String> map = findDicItems(dicCode);
		return map == null ? null : map.get(itemCode);
	}
	
	/**
	 * 查找字典项，包括字典code
	 */
	@SuppressWarnings("unchecked")
	public LinkedHashMap<String, LinkedHashMap<String, String>> findDicItems(){
		if (ContainerKit.contains("dic")) {
			return (LinkedHashMap<String, LinkedHashMap<String, String>>) ContainerKit.get("dic");
		}
		LinkedHashMap<String, LinkedHashMap<String, String>> map = new LinkedHashMap<>();
		List<Record> records = Db.find(getSqlPara("pdc.dic_item.findDicItems"));
		for (Record record : records) {
			LinkedHashMap<String, String> valueMap = null;
			String key = record.get("dic_code");
			if (map.containsKey(key)) {
				valueMap = map.get(key);
			}else {
				valueMap = new LinkedHashMap<>();
				map.put(key, valueMap);
			}
			valueMap.put(record.getStr("item_code"), record.getStr("item_value"));
		}
		return map;
	}
}